/*
 * Connection.java
 *
 * Created on 8 November 2006, 19:50
 *
 */

package org.foment.joliage3.sql;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import static org.foment.joliage3.core.logging.Logger.log;
import org.foment.joliage3.core.logging.Logger;

import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;

/**
 * Class containing static methods for basic SQL (JDBC) operations
 * @author ivan
 */
public class Database
{
  // Connection related
    private static String jdbcURL = "jdbc:mysql://192.168.1.200/gem?user=root&password=d8k24m11&characterSetResults=UTF-8&characterEncoding=UTF8&useUnicode=true";
    private static String jdbcDriver = "com.mysql.jdbc.Driver";

    public static String getJDBCURL() { return jdbcURL; }
    public static String getJDBCDriver() { return jdbcDriver; }

    private static java.sql.Connection _sqlConnection = null;

    public static java.sql.Connection getConnection()
    {
        try
        {
            java.sql.Connection conn;
            do
            {
                conn = PoolDataSource.getInstance().getConnection();
                if( conn != null)
                {
                    return conn;
                }
                System.out.println("Pokusavam da dobijam vezu!");
            }
            while( true );       
        }
        catch( SQLException e )
        {
            e.printStackTrace();
        }
        catch (Exception e )
        {
            e.printStackTrace();
        }

        return null;

        /*
        if (!isConnected())
        {
            // ako je veza prekinuta, pokusavamo da se povezemo ponovo...
            reconnect();
        }
        // ako je uspelo povezivanje, vracamo objekat veze.
        return _sqlConnection;
         * */
    }
 
  /**
   * Connects to the database using JDBC address from config file.
   * Config file is config.sql resource bundle. The driver is also
   * loaded uding the information from the config file.
   * @return true on success
   */

public static boolean connect()
{
    if (_sqlConnection != null) return true;
    
    java.util.Properties prop = new java.util.Properties();
    try
    {
        prop.load( new FileInputStream("config/sql.properties"));
      
        if( prop.getProperty("jdbcURL") != null)
        {
            System.out.println("found url");
            jdbcURL = prop.getProperty("jdbcURL");
        }
        if( prop.getProperty("jdbcDriver") != null)
        {
            jdbcDriver = prop.getProperty("jdbcDriver");
        }
        System.out.println( jdbcDriver );
        System.out.println( jdbcURL );
    }
    // In case we have not found config, we have hardcoded values in jdbcURL and jdbcDriver
    catch( IOException e )
    {
        e.printStackTrace();
    }
    
    try
    {
        java.sql.DriverManager.setLoginTimeout(5);
        java.sql.Driver driver = (java.sql.Driver) Class.forName( jdbcDriver ).newInstance();
        _sqlConnection = java.sql.DriverManager.getConnection( jdbcURL );
    }
    catch ( java.sql.SQLException e )
    {
      log("joliage3", "org.foment.joliage3.sql.Database", Logger.FATAL_ERROR, "Can't connect to DB server", e);
      return false; 
    }
    catch ( Exception e )
    {
        log("joliage3", "org.foment.joliage3.sql.Database", Logger.FATAL_ERROR, "Unknown error while loading the driver or the connection", e);
        return false;
    }
    if (_sqlConnection == null)
    {
        log("joliage3", "org.foment.joliage3.sql.Database", Logger.FATAL_ERROR, "Connection not established", null);
        return false;
    }
    
    return true;
  }
  
  /**
   * Closes the database connection
   * @return true on success
   */
    public static boolean disconnect()
    {
        try
        {
            _sqlConnection.close();
        }
        catch (java.sql.SQLException e)
        {
            log("joliage3", "org.foment.joliage3.sql.Database", Logger.ERROR, "Can not disconnect", e);
            _sqlConnection = null;
            return false;
        }
        _sqlConnection = null;
        return true;
    }
  
  /**
   * Closes the current database connection. If the closure succeeds, the
   * connection is reestablished.
   * @return true on success
   */
    public static boolean reconnect()
    {
        return disconnect() && connect();
    }
  
  /**
   * Checks if there is a connection to the database
   * @return true if exists
   */
    public static boolean isConnected()
    {
        boolean connected = true;
        try
        {
            // stavljamo 60 sekundi kao maksimalno vreme za povezivanje.
            connected = _sqlConnection.isValid(60);
        }
        catch (SQLException ex)
        {
            java.util.logging.Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connected;
    }
  
  /**
   * Returns the Table object for the specified table name
   * @param tableName table name
   * @return table object
   */
    public static Table getTable(String tableName) throws SQLException
    {
        return Table.getTable(tableName);
    }
}
